import { useSelector, useDispatch } from "react-redux";
import Creators from "../store/actions";
import { useCallback } from "react";
import OrderApi from "../api/order";

export const useOrder = () => {
  const order = useSelector(state => state.order);
  const dispatch = useDispatch();


  // 获取订单当页数据
  const { curPage, eachPage } = order;
  const getOrder = useCallback(async () => {
    const data = await OrderApi.get({ curPage, eachPage });
    console.log(data);
    dispatch(Creators.getOrder(data));
  }, [curPage, eachPage, dispatch]);

  // 修改当前页
  const setCurPage = useCallback((curPage) => {
    dispatch(Creators.orderSetCurPage({ curPage }))
  }, [dispatch]);

  // 修改每页显示条数
  const setEachPage = useCallback((eachPage) => {
    dispatch(Creators.orderSetEachPage({ eachPage }))
  }, [dispatch])


  // // 新增订单
  const addOrder = useCallback(async ({ commodities, isAffirmReceive, isPaySuccess, orderTime, totalPrice, userId }) => {
    return await OrderApi.addOrder({ commodities, isAffirmReceive, isPaySuccess, orderTime, totalPrice, userId });
  }, []);

  // 删除订单
  const delOrder = useCallback(async (_id) => {
    await OrderApi.delOrder(_id);
  }, []);

  // 通过商品和id名称查询订单
  const findOrder = useCallback(async (selectData) => {
    // console.log({ ...selectData });
    const { rows, result } = await OrderApi.findOrder({ ...selectData });
    // console.log(rows, result);
    dispatch(Creators.orderGetSearch({ rows }));
    return result;
  }, []);

  // 确认商品收货
  const changeState = useCallback(async (_id) => {
    return await OrderApi.changeState(_id);
  }, [])


  return [order, { getOrder, setCurPage, setEachPage, addOrder, delOrder, findOrder, changeState }];
}